package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.itheima.mapper.ArticleContentMapper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.service.SearchService;
import com.itheima.dto.SearchDto;
import com.itheima.po.Article;
import com.itheima.po.ArticleContent;
import com.itheima.vo.SearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author :wujunjie
 * createTime :2022-12-29 10:10
 * description :
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleContentMapper articleContentMapper;

    @Override
    public List<SearchVo> search(SearchDto searchDto) {

        MPJLambdaWrapper<Article> lqw = new MPJLambdaWrapper<>();
        Instant instant = Instant.ofEpochMilli(Long.parseLong(searchDto.getMinBehotTime()));
        LocalDateTime publishTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        lqw.lt(Article::getPublishTime, publishTime);

        lqw.like(Article::getTitle,searchDto.getSearchWords());

        String last = "limit " + searchDto.getPageNum()+","+searchDto.getPageSize();
        lqw.last(last);

        List<Article> articles = articleMapper.selectList(lqw);

        List<SearchVo> searchVos = BeanUtil.copyToList(articles, SearchVo.class);
        if (CollectionUtils.isEmpty(searchVos))
        {
            return null;
        }
        Set<Long> ids = searchVos.stream().filter(Objects::nonNull).map(SearchVo::getId).collect(Collectors.toSet());

        List<Long> idList=new ArrayList<>(ids);
        MPJLambdaWrapper<ArticleContent> contentWrapper= new MPJLambdaWrapper<>();
        contentWrapper.in(ArticleContent::getArticleId,idList);
        List<ArticleContent> articleContents = articleContentMapper.selectList(contentWrapper);
        Map<Long, List<ArticleContent>> articleContentMap = articleContents.stream().collect(Collectors.groupingBy(ArticleContent::getArticleId));
        for (SearchVo searchVo : searchVos) {
            searchVo.setContent(articleContentMap.get(searchVo.getId()).get(0).getContent());
        }
        return searchVos;
    }
}
